var express = require('express')

var DB = require('../../modules/db')

var router = express.Router()  /*可使用express.Router类创建模块化,可挂载的路由句柄*/

var md5 = require('md5-node')
//登录
router.get('/',function (req, res) {
    res.render('admin/login')
})
//登出
router.get('/out',function (req, res) {

    req.session.destroy(function (err) {
        if (err) {
            console.log('destroy' + err)
        }else {
            res.redirect('/admin/login')
        }
    })

})

router.post('/doLogin',function (req, res) {

    // console.log(req.body) /*获取post数据*/

    //1、获取数据

    //2、连接数据库
    DB.find('users',{
        "userAccount":req.body.userName,
        "password":md5(req.body.password)
    },function (err,data) {
        if (err) {
            console.log('查询失败')
        }else {
            console.log(data)

            if (data.length > 0) {
                // console.log('登录成功')

                //保存用户信息
                req.session.userInfo = data[0]

                res.redirect('/admin/product') /*登录成功跳转到商品列表*/
            }else {
                res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"})
                res.end("<script>alert('登录失败');location.href='/admin/login'</script>")
            }
        }
    })
})



module.exports = router